package com.ideaaedi.springcloud.jd.commonspring.mybatis.handler;

import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.EnumTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 枚举处理器
 * <p>
 *     null存数据库时存""，取值时""取出来为null
 * </p>
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.5.B
 */
public class EnumEmptyNullHandler<E extends Enum<E>> extends EnumTypeHandler<E> {
    
    private final Class<E> type;
    
    public EnumEmptyNullHandler(Class<E> type) {
        super(type);
        this.type = type;
    }
    
    @Override
    public void setParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i, BaseConstant.EMPTY);
            return;
        }
        super.setParameter(ps, i, parameter, jdbcType);
    }
    
    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
        return StringUtils.isBlank(s) ? null : Enum.valueOf(type, s);
    }
    
    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return StringUtils.isBlank(s) ? null : Enum.valueOf(type, s);
    }
    
    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return StringUtils.isBlank(s) ? null : Enum.valueOf(type, s);
    }
}

